<template>
  <div class="app-container">
    <div :class="['filter-container', 'open']" style="height: 55px !important">
      <!-- 展开状态下的筛选框 -->
      <el-form ref="form" :inline="true" :model="form" label-width="80px">
        <el-form-item label="集群名称" label-width="100px">
          <el-input v-model="form.name" placeholder clearable />
        </el-form-item>
        <el-form-item>
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
            >查询</el-button
          >
          <el-button
            class="filter-item"
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-edit-outline"
            @click="handleReset"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-button
      class="filter-item"
      type="primary"
      style="margin-bottom: 15px"
      @click="handleCreate"
      >新增</el-button
    >
    <el-table height="690" :data="list" highlight-current-row>
      <el-table-column
        prop="cloudId"
        header-align="center"
        align="center"
        label="id"
      />
      <el-table-column
        prop="cloudName"
        header-align="center"
        align="center"
        label="集群名称"
      />
      <el-table-column header-align="center" align="center" label="所有服务">
        <template slot-scope="scope">
          <span
            v-for="(item, index) in scope.row.projectIds"
            :key="item.projectId"
          >
            <el-popover placement="top" trigger="hover">
              <div
                style="
                  width: 200px;
                  display: flex;
                  justify-content: left;
                  flex-wrap: wrap;
                  color: #1890ff;
                "
              >
                <el-button
                  size="mini"
                  type="primary"
                  @click="developLowCode(item)"
                  style="
                    margin-left: left;
                    margin-left: 10px;
                    margin-bottom: 10px;
                  "
                  >开发</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  style="margin-left: 35px; margin-bottom: 10px"
                  @click.stop="handleDeploy(item, scope.row)"
                  :loading="item.deployLoading"
                  >部署</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleLook(item.projectId)"
                  >查看详情</el-button
                >
                <el-button size="mini" type="primary" @click="handlesetUp(item)"
                  >设置服务名</el-button
                >
              </div>
              <span slot="reference" style="cursor: pointer">
                {{
                  `${
                    item.projectName +
                    (index == scope.row.projectIds.length - 1 ? "" : ";")
                  }`
                }}
              </span>
            </el-popover>
          </span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="网关">
        <template slot-scope="scope">
          <div>
            <el-popover placement="top" trigger="hover">
              <el-button
                type="primary"
                style="margin-left: 20px"
                @click="handleRouter(scope.row.gatewayConfigId)"
                >配置路由</el-button
              >
              <span slot="reference" style="cursor: pointer">
                {{ scope.row.gatewayProjectName }}
              </span>
            </el-popover>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="nacosAddr"
        header-align="center"
        align="center"
        label="服务注册中心地址"
      />
      <el-table-column
        header-align="center"
        align="center"
        width="180"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button type="text" size="small" @click="handlesLook(scope.row)"
            >查看</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleArrange(scope.row)"
            :loading="scope.row.caozuoLoading"
            >部署</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-if="dialogFormVisible"
      title="查看详情"
      :visible.sync="dialogFormVisible"
      width="30%"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="temp.name"
            :disabled="isDisabled"
            placeholder
            clearable
          />
        </el-form-item>
        <el-form-item label="项目类型" prop="type">
          <el-select
            v-model="temp.type"
            placeholder
            clearable
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in importanceOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目英文名称" prop="enName">
          <el-input
            v-model="temp.enName"
            :disabled="isDisabled"
            placeholder
            clearable
          />
        </el-form-item>
        <el-form-item label="项目简称" prop="shortName">
          <el-input
            v-model="temp.shortName"
            :disabled="isDisabled"
            placeholder
            clearable
          />
        </el-form-item>
        <el-form-item label="项目管理员">
          <el-select
            v-model="temp.adminId"
            placeholder
            clearable
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in templateLists"
              :key="item.userId"
              :label="item.username"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目模板" prop="projectTemplateId">
          <el-select
            v-model="temp.projectTemplateId"
            placeholder
            clearable
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in projectTemplateLists"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-select
            v-model="temp.businessType"
            placeholder
            clearable
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in businessLists"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目描述">
          <el-input
            v-model="temp.description"
            type="textarea"
            placeholder
            clearable
            :disabled="isDisabled"
          />
        </el-form-item>
        <el-form-item label="引入类">
          <el-select v-model="temp.ids" multiple placeholder="请选择">
            <el-option
              v-for="item in idsLists"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务名">
          <el-input
            v-model="temp.serverName"
            placeholder
            clearable
            :disabled="isDisabled"
          />
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      v-if="addVisible"
      :title="titleDialog"
      :visible.sync="addVisible"
      :modal="false"
    >
      <el-form
        ref="dataRefForm"
        :model="FormObj"
        label-position="right"
        label-width="130px"
        :rules="dialogrules"
      >
        <el-form-item label="集群名称" prop="cloudName">
          <el-input
            v-model="FormObj.cloudName"
            :disabled="isDisabled"
            placeholder
            clearable
          />
        </el-form-item>
        <el-form-item label="选择服务" prop="project_Ids">
          <el-checkbox-group v-model="FormObj.project_Ids">
            <el-checkbox
              v-for="city in gatewangguanLists"
              :label="city.id"
              :key="city.id"
              >{{ city.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="选择网关" prop="gatewayId">
          <el-select
            v-model="FormObj.gatewayId"
            clearable
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in gateWayLists"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务注册中心地址" prop="nacosAddr">
          <el-input
            v-model="FormObj.nacosAddr"
            :disabled="isDisabled"
            placeholder
            clearable
            style="width: 58%; margin-right: 5px"
          />
          <span style="color: red"
            >所有已选择服务的服务注册中心地址将设置为此地址</span
          >
        </el-form-item>
      </el-form>
      <div v-show="!isDisabled" slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="hanldeAddSave">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="addSureVisible"
      title="设置服务名"
      :visible.sync="addSureVisible"
      :modal="false"
      width="30%"
    >
      <el-form
        ref="datasureRefForm"
        :model="setUpObj"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="项目名:">
          <span>{{ setUpObj.projectName }}</span>
        </el-form-item>
        <el-form-item label="旧服务名:">
          <span>{{ setUpObj.oldName }}</span>
        </el-form-item>
        <el-form-item
          label="新服务名:"
          prop="name"
          :rules="[
            {
              required: true,
              message: '请输入新服务名,只能输入英文名',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="setUpObj.name"
            @input="
              (value) => (setUpObj.name = value.replace(/[^a-zA-Z0-9]/g, ''))
            "
            placeholder="请输入服务名,只能输入英文名"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addSureVisible = false">取消</el-button>
        <el-button type="primary" @click="hanldesetUpSave">确认</el-button>
      </div>
    </el-dialog>
    <configurationeEdit
      :dialogVisible="dialogVisible"
      v-if="dialogVisible"
      :editId="editId"
    />
  </div>
</template>

<script>
import {
  projectModelsave,
  projectModelupdate,
  projectModellist,
  datasourcelistfindPage,
  projectlistsTemplate,
  jlcpCloudProject,
  projectsave,
  projectupdate,
  projectgenerate,
  projectConfigfindPage,
  datasourceconfigTable,
  defaultClass,
  projectfindPage,
  projectJlcpSave,
  projectJlcpUpdate,
  projectJlcpDelete,
  projectManageinfo,
  updateApplicationName,
  getConfigValue,
  getConfigDeploy,
} from "@/api/article";
import configurationeEdit from "./configurationeEdit";
import { getUserList } from "@/api/permission";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination 分页组件
import { getToken } from "@/utils/auth";
import qs from "qs";
const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" },
];

export default {
  name: "cloudListPath",
  components: { Pagination, configurationeEdit },
  directives: { waves }, // 指令
  data() {
    const validatePass = (rule, value, callback) => {
      //正则的开始(^)和结束($)一般用于表单的校验
      const resg = /^[\u4e00-\u9fa5a-zA-Z]+$/g;
      if (resg.test(value)) {
        callback();
      } else {
        callback("请输入项目名称");
      }
    };
    const validatePass1 = (rule, value, callback) => {
      const resg = /^[^\u4e00-\u9fa5]+$/g;
      if (resg.test(value)) {
        callback();
      } else {
        callback("请输入英文名称");
      }
    };
    const validatePass2 = (rule, value, callback) => {
      const res = /^([a-zA-Z0-9.-]+)(:[0-9]+)$/;
      if (res.test(value)) {
        callback();
      } else {
        callback("请输入正确的服务注册中心地址");
      }
    };
    return {
      dialogrules: {
        cloudName: [
          {
            required: true,
            message: "请输入集群名称",
            trigger: "blur",
          },
        ],
        project_Ids: [
          {
            required: true,
            message: "请至少选择一个单体项目",
            trigger: "change",
          },
        ],
        gatewayId: [
          {
            required: true,
            message: "请选择网关",
            trigger: "change",
          },
        ],
        nacosAddr: [{ validator: validatePass2, trigger: "blur" }],
      },
      setUpObj: {
        projectId: undefined,
        projectName: "",
        name: "",
      },
      addSureVisible: false,
      titleDialog: "新增",
      gateWayLists: [],
      gatewangguanLists: [],
      checkedLists: [],
      //新增
      addVisible: false,
      idsLists: [],
      filterCode: "",
      codeDataLists: [],
      tablechangeLists: [],
      datasourceRule: {
        datasourceConfigId: [
          { required: true, message: "请选择数据源", trigger: "change" },
        ],
        moduleName: [
          { required: true, message: "请输入子模块", trigger: "blur" },
        ],
      },
      generationCodeObj: {
        datasourceConfigId: "",
        moduleName: "",
        delPrefix: "",
        author: "",
      },
      generationCodeVisible: false,
      authorLists: [],
      modelLists: [],
      generationObj: {},
      GenerationData: [],
      generationVisible: false,
      tableData: [],
      peizhiVisible: false,
      // 筛选框的 form 表单
      isDisabled: false,
      form: {
        name: "",
      },
      tableKey: 0,
      list: [], // 表格数据
      total: 0, // 总条数
      listLoading: true, // 表格加载数据时的 loading
      importanceOptions: [
        {
          code: 1,
          name: "web后台",
        },
        {
          code: 2,
          name: "客户端",
        },
        {
          code: 3,
          name: "app",
        },
        {
          code: 4,
          name: "小程序",
        },
      ],
      templateLists: [],
      businessLists: [
        {
          code: 1,
          name: "标准后台类",
        },
        {
          code: 2,
          name: "ERP类",
        },
        {
          code: 3,
          name: "OA类",
        },
      ],
      projectTemplateLists: [],
      calendarTypeOptions, // 类型的下拉选内容
      sortOptions: [
        {
          code: 1,
          name: "初始状态",
        },
        {
          code: 2,
          name: "正在生成",
        },
        {
          code: 3,
          name: "已生成",
        },
        {
          code: 4,
          name: "生成失败",
        },
      ],
      statusOptions: ["published", "draft", "deleted"], // 新增和修改弹框里面的 Status 下拉框
      temp: {
        // 新增和修改弹框 的 form 表单
        name: "",
        type: "",
        enName: "",
        shortName: "",
        adminId: "",
        projectTemplateId: "",
        businessType: "",
        description: "",
      },
      FormObj: {
        projectIds: [],
        project_Ids: [],
      },
      rules: {
        // 表单验证
        name: [{ required: true, validator: validatePass, trigger: "blur" }],
        enName: [{ required: true, validator: validatePass1, trigger: "blur" }],
        shortName: [
          { required: true, message: "请输入项目简称", trigger: "blur" },
        ],
        projectTemplateId: [
          { required: true, message: "请选择项目模板", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择项目类型", trigger: "change" },
        ],
        businessType: [
          { required: true, message: "请选择业务类型", trigger: "change" },
        ],
      },
      dialogFormVisible: false, // 弹框展示隐藏
      dialogStatus: "", // 弹框新增或者修改
      textMap: {
        // 弹框的标题
        update: "编辑",
        create: "新增",
      },
      downloadLoading: false, // 导出按钮 的 loading
      moudleId: "",
      codeId: "",
      tableNames: [],
      pickerOptions1: {
        disabledDate: (time) => {
          if (this.form.endTime) {
            return time.getTime() > new Date(this.form.endTime).getTime();
          }
        },
      },
      pickerOptions2: {
        disabledDate: (time) => {
          if (this.form.startTime) {
            return (
              time.getTime() <
              new Date(this.form.startTime).getTime() - 86400000
            );
          }
        },
      },
      dialogVisible: false,
      editId: 0,
      peizhiId: 0,
    };
  },
  computed: {
    _codeDataLists_() {
      if (this.filterCode) {
        return this.codeDataLists.filter((dataNews) => {
          return Object.keys(dataNews).some((key) => {
            return (
              String(dataNews[key])
                .toLowerCase()
                .indexOf(this.filterCode.toLowerCase()) > -1
            );
          });
        });
      }
      return this.codeDataLists;
    },
    compIcon() {
      return (item) => {
        return item.status == 1
          ? "el-icon-s-help"
          : item.status == 2
          ? "el-icon-loading"
          : item.status == 3
          ? "el-icon-success"
          : "el-icon-error";
      };
    },
    styleObj() {
      return (item) => {
        let color =
          item.status == 1
            ? "#1890ff"
            : item.status == 2
            ? "#d69d05"
            : item.status == 3
            ? "#67c23a"
            : "#f56c6c";
        let background =
          item.status == 1
            ? "#d1ddea"
            : item.status == 2
            ? "#e3e2df"
            : item.status == 3
            ? "rgb(232, 255, 234)"
            : "rgb(255, 236, 232)";
        return {
          color,
          background,
        };
      };
    },
    showStatus() {
      return (item) => {
        return item.status == 1
          ? "初始状态"
          : item.status == 2
          ? "正在生成"
          : item.status == 3
          ? "已生成"
          : "生成失败";
      };
    },
  },
  async created() {
    await this.getUserList();
    this.getList();
    this.projectlistsTemplate();
    await this.projectfindPage();
    await this.project_findPage();
  },
  methods: {
    async handleDeploy(item, row) {
      try {
        this.$set(item, "deployLoading", true);
        this.$set(row, "caozuoLoading", true);
        const res = await getConfigDeploy(item.projectId);
        if (res.code == 200) {
          if (res.data) {
            this.$message({
              message: `${item.projectName}部署成功`,
              type: "success",
            });
          } else {
            this.$message({
              message: `${item.projectName}部署失败`,
              type: "warning",
            });
          }
        }
      } catch (err) {
        this.$message({
          message: `${item.projectName}部署失败`,
          type: "warning",
        });
      } finally {
        this.$set(item, "deployLoading", false);
        this.$set(row, "caozuoLoading", false);
      }
    },
    handleRouter(gatewayConfigId) {
      this.dialogVisible = true;
      this.editId = gatewayConfigId;
    },
    async handleArrange(row) {
      const promises = [];
      this.$set(row, "caozuoLoading", true);

      for (const item of row.projectIds) {
        this.$set(item, "deployLoading", true);
        const promise1 = getConfigDeploy(item.projectId);
        promises.push(promise1);
        promise1
          .then((res) => {
            if (res.code == 200) {
              if (res.data) {
                this.$message({
                  message: `${item.projectName}部署成功`,
                  type: "success",
                });
              } else {
                this.$message({
                  message: `${item.projectName}部署失败`,
                  type: "warning",
                });
              }
            }
          })
          .catch((err) => {
            this.$message({
              message: `${item.projectName}部署失败`,
              type: "warning",
            });
          });
      }
      const promise2 = getConfigDeploy(row.gatewayId);
      promises.push(promise2);
      promise2
        .then((res) => {
          if (res.code == 200) {
            if (res.data) {
              this.$message({
                message: `${row.gatewayProjectName}部署成功`,
                type: "success",
              });
            } else {
              this.$message({
                message: `${row.gatewayProjectName}部署失败`,
                type: "warning",
              });
            }
          }
        })
        .catch((err) => {
          this.$message({
            message: `${row.gatewayProjectName}部署失败`,
            type: "warning",
          });
        });
      await Promise.allSettled(promises);
      this.$set(row, "caozuoLoading", false);
      row.projectIds.forEach((item) => {
        item.deployLoading = false;
      });
    },
    async handlesetUp(item) {
      this.addSureVisible = true;
      this.setUpObj.projectName = item.projectName;
      this.setUpObj.projectId = item.projectId;
      this.setUpObj.name = "";
      const result = await getConfigValue(item.projectId);
      if (result.code == 200) {
        this.$set(this.setUpObj, "oldName", result.data);
      } else {
        this.$set(this.setUpObj, "oldName", "");
      }
    },
    hanldesetUpSave() {
      this.$refs.datasureRefForm.validate(async (valid) => {
        if (valid) {
          const res = await updateApplicationName(
            this.setUpObj.projectId,
            this.setUpObj.name
          );
          if (res?.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success",
            });
            this.addSureVisible = false;
          }
        }
      });
    },
    // 新增数据-打开弹框
    handleCreate() {
      this.titleDialog = "新增";
      this.isDisabled = false;
      this.addVisible = true;
      this.FormObj = {
        projectIds: [],
        project_Ids: [],
      };
      this.projectfindPage();
    },
    async handleEdit(item) {
      this.titleDialog = "编辑";
      this.isDisabled = false;
      this.lookEditCommon(item);
    },
    async handlesLook(item) {
      this.titleDialog = "查看";
      this.isDisabled = true;
      this.lookEditCommon(item);
    },
    async lookEditCommon(item) {
      this.addVisible = true;
      this.FormObj = JSON.parse(JSON.stringify(item));
      console.log(this.FormObj, 78963100000000);
      this.$set(
        this.FormObj,
        "project_Ids",
        this.FormObj.projectIds.map((list) => list.projectId)
      );
    },
    hanldeAddSave() {
      this.$refs.dataRefForm.validate(async (valid) => {
        if (valid) {
          let res = null;
          this.FormObj.projectIds = JSON.stringify(this.FormObj.project_Ids);
          if (this.FormObj.cloudId) {
            res = await projectJlcpUpdate(this.FormObj);
          } else {
            res = await projectJlcpSave(this.FormObj);
          }
          if (res?.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success",
            });
            this.addVisible = false;
            this.getList();
          }
        }
      });
    },
    async handleDelete(item) {
      this.$confirm(`确定要进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await projectJlcpDelete([item.cloudId]);
        if (res?.code === 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getList();
        }
      });
    },
    async project_findPage() {
      this.gatewangguanLists = [];
      const res = await projectfindPage({
        name: "",
        type: "",
        startTime: "",
        endTime: "",
        status: "",
      });
      if (res?.code === 200) {
        this.gatewangguanLists = res.data;
      }
    },
    async projectfindPage() {
      this.gateWayLists = [];
      const res = await projectfindPage({
        name: "",
        type: "",
        startTime: "",
        endTime: "",
        status: "",
        // page: 1,
        // limit: 20,
        businessType: 4,
      });
      if (res?.code === 200) {
        this.gateWayLists = res.data;
      }
    },
    async defaultClass() {
      this.idsLists = [];
      const res = await defaultClass();
      if (res?.code === 200) {
        this.idsLists = res.data;
      }
    },
    developLowCode(item) {
      sessionStorage.setItem("developLowCodeId", item.projectId);
      sessionStorage.setItem("developLowCodeName", item.projectName);
      sessionStorage.setItem("developLowCodeTitle", item.projectName);
      this.$router.push({
        name: "developLowCode",
      });
    },
    async handleExport(item) {
      this.$message({
        showClose: true,
        message: "正在导出...",
        type: "warning",
        showClose: true,
      });
      window.location.href = `${
        process.env.VUE_APP_BASE_API
      }/projectManage/project/download?${qs.stringify({
        id: item.id,
        token: getToken(),
      })}`;
    },
    async datasourcelistfindPage() {
      this.generationCodeObj.datasourceConfigId = "";
      const res = await datasourcelistfindPage();
      if (res?.code === 200) {
        this.tablechangeLists = res.data;
        this.generationCodeObj.datasourceConfigId =
          this.tablechangeLists?.length && this.tablechangeLists[0].id;
      }
    },
    // 选择表table数据
    async datasourceconfigTable(id) {
      this.codeDataLists = [];
      const res = await datasourceconfigTable(id);
      if (res?.code === 200) {
        this.codeDataLists = res.data;
      }
    },
    selectionChange(valObj) {
      this.tableNames = valObj;
    },
    // 生成接口
    handleClickgenerate() {
      const tableNames = this.tableNames.map((item) => item.tableName);
      this.$refs.generat_ionCodeObj.validate((valid) => {
        if (valid) {
          const config = JSON.stringify({
            // ...this.generationObj,
            moduleId: this.moudleId,
            projectId: this.codeId,
            ...this.generationCodeObj,
            tableNames,
          });
          this.$router.push(
            `/codeManagement/result?config=${config}&project=true`
          );
        }
      });
    },

    handleCclickAdd() {
      this.GenerationData.push({
        name: "",
        viewName: "",
        remark: "",
        isSave: true,
      });
    },
    async projectModellist(id) {
      this.GenerationData = [];
      const res = await projectModellist(id);
      if (res?.code === 200) {
        this.GenerationData = res.data;
      }
    },
    async handleEditSave(row) {
      if (row.id) {
        const res = await projectModelupdate({
          projectId: this.codeId,
          id: row.id,
          name: row.name,
          viewName: row.viewName,
          remark: row.remark,
        });
        if (res?.code === 200) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          row.isSave = false;
        }
      } else {
        const res = await projectModelsave({
          projectId: this.codeId,
          name: row.name,
          viewName: row.viewName,
          remark: row.remark,
        });
        if (res?.code === 200) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          row.id = res.data.id;
          row.isSave = false;
        }
      }
    },
    async handleEditUpdate(row) {
      this.$set(row, "isSave", true);
    },
    async handleCodeGeneration(row) {
      this.moudleId = row.id;
      this.generationCodeVisible = true;
      this.filterCode = "";
      this.generationCodeObj.moduleName = "";
      this.generationCodeObj.delPrefix = "";
      this.generationCodeObj.author = "";
      await this.datasourcelistfindPage();
      this.datasourceconfigTable(
        this.tablechangeLists?.length && this.tablechangeLists[0].id
      );
    },
    handleGeneration(item) {
      this.generationVisible = true;
      this.generationObj = {};
      this.codeId = item.id;
      this.projectModellist(item.id);
    },
    // 获取表格数据
    getList() {
      this.listLoading = true;
      jlcpCloudProject(this.form.name).then((response) => {
        this.list = response.data;
        this.list.forEach((item) => {
          const projectName = item.projectIds.reduce((pre, next, index) => {
            pre +=
              index == item.projectIds.length - 1
                ? next.projectName
                : next.projectName + ";";
            return pre;
          }, "");
          this.$set(item, "projectbaohan", projectName);
        });
        this.total = response.data.totalCount;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    async getUserList() {
      this.templateLists = [];
      const res = await getUserList();
      if (res?.code === 200) {
        this.templateLists = res.data;
      }
    },

    async projectlistsTemplate() {
      this.projectTemplateLists = [];
      const res = await projectlistsTemplate();
      if (res?.code === 200) {
        this.projectTemplateLists = res.data;
      }
    },
    async handleLook(projectId) {
      this.isDisabled = true;
      this.dialogFormVisible = true;
      const res = await projectManageinfo(projectId);
      if (res.code == 200) {
        this.temp = JSON.parse(JSON.stringify(res.data));
      } else {
        this.temp = {};
      }
      const result = await getConfigValue(projectId);
      if (result.code == 200) {
        this.$set(this.temp, "serverName", result.data);
      } else {
        this.$set(this.temp, "serverName", "");
      }
    },
    // 重新获取表格数据 页码归为1
    handleFilter() {
      this.form.page = 1;
      this.getList();
    },
    handleReset() {
      this.form = {
        name: "",
        type: "",
        startTime: "",
        endTime: "",
        status: "",
        page: 1,
        limit: 20,
      };
      this.getList();
    },

    // 新增数据-表单提交
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          projectsave(this.temp).then((res) => {
            if (res?.code === 200) {
              this.dialogFormVisible = false;
              this.$message({
                // message: res.message,
                message: "新增成功",
                type: "success",
              });
              this.getList();
            }
          });
        }
      });
    },
    // 修改 -- 提交表单
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          projectupdate(this.temp).then(() => {
            this.dialogFormVisible = false;
            this.$message({
              // message: res.message,
              message: "修改成功",
              type: "success",
            });
            this.getList();
          });
        }
      });
    },
    async handleGenerate(item) {
      this.$confirm(`确定要进行生成操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await projectgenerate(item.id);
        if (res?.code === 200) {
          this.$message({
            // message: res.message,
            message: res.message,
            type: "success",
          });
          this.getList();
        }
      });
    },
    async projectConfigfindPage(id) {
      this.tableData = [];
      const res = await projectConfigfindPage(id);
      if (res?.code === 200) {
        this.tableData = res.data;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import "~@/styles/layout-table.scss";
$rowLength: 2;
@media all and (min-width: 1659px) {
  $rowLength: 2;
  @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
  $rowLength: 3;
  @include calculation($rowLength: $rowLength);
}
</style>
<style>
.icons_Style {
  display: inline-block;
  padding: 7px 15px;
  font-size: 12px;
  border-radius: 3px;
  opacity: 1.5;
  margin-top: 0px;
}
</style>
